package com.gui.consistency.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gui.consistency.service.ConsistencyService;
import com.gui.entity.Person;
import com.gui.lock.mapper.PersonMapper;
import com.gui.utils.Sleeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ConsistencyServiceImpl extends ServiceImpl<PersonMapper, Person> implements ConsistencyService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PersonMapper personMapper;

    @Override
    public Person query(Integer id) {
        String key = "person:cache:" + id;
        String personStr = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(personStr)) {
            return JSONObject.parseObject(personStr, Person.class);
        }
        Person person = personMapper.selectById(id);
        if (person == null) {
            throw new RuntimeException("角色不存在");
        }
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(person), 10, TimeUnit.MINUTES);
        return person;
    }

    @Override
    public void deleteUpdate(Person person) {
        String key = "person:cache:" + person.getId();
        stringRedisTemplate.delete(key);
        updateDatabase(person);

    }

    private void updateDatabase(Person person) {
        Sleeper.sleep(TimeUnit.SECONDS, 5);
        personMapper.updateById(person);
    }
}
